<template>
  <div>
    <el-card class="sur-card">
      <div class="sur-card-title" slot="header">
        <span>手机壳模型</span>
        <el-button type="text" @click="showAddRowDialog">添加模型</el-button>
      </div>
      <el-row>
        <div class="search-section">
          <el-form :inline="true">
            <el-form-item>
              <el-select
                size="small"
                v-model="pageVo.brandId"
                placeholder="请选择品牌"
              >
                <el-option
                  v-for="brand in brands"
                  :key="brand.id"
                  :label="brand.brandName"
                  :value="brand.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="pageVo.moldName"
                size="small"
                placeholder="请输入模具名称"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="pageVo.moldCode"
                size="small"
                placeholder="请输入模具编码"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button size="small" icon="el-icon-search" @click="onSearch"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  icon="el-icon-refresh"
                  @click="onClearSearchForm"
                  >刷新</el-button
                >
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>
      </el-row>
      <el-table :data="mbCaseMoldList" border v-loading="loadingTable">
        <el-table-column
          label="序号"
          type="index"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="brandId"
          label="品牌ID"
          align="center"
          :formatter="brandFormatter"
        ></el-table-column>
        <el-table-column
          prop="moldName"
          label="型号"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="moldCode"
          label="模具编码"
          align="center"
        ></el-table-column>
        <el-table-column prop="backImg" label="底图" align="center">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.backImg"
              fit="contain"
              style="width: 100px;height: 100px"
              :preview-src-list="Array.of(scope.row.backImg)"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="overlayImg" label="顶层透明图" align="center">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.overlayImg"
              :preview-src-list="Array.of(scope.row.overlayImg)"
              fit="contain"
              style="width: 100px;height: 100px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | dateFormatMin }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" @click="onEditRow(scope.row)"
              >编辑
            </el-button>
            <el-button type="danger" @click="onDeleteRow(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-pagination
          class="page-section"
          background
          @current-change="onPaging"
          :page-size="pageVo.size"
          @size-change="handleSizeChange"
          :page-sizes="[20, 50, 100, 200]"
          layout="total,sizes,prev, pager, next"
          :total="pageVo.total"
        />
      </el-row>
    </el-card>
    <!--    编辑row对话框-->
    <el-dialog title="编辑mbCaseMold" :visible.sync="editRowVisible">
      <el-form
        :model="mbCaseMoldModel"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="适用品牌">
          <el-select size="small" v-model="mbCaseMoldModel.brandId" placeholder="请选择品牌">
            <el-option
              v-for="brand in brands"
              :key="brand.id"
              :label="brand.brandName"
              :value="brand.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模具名称">
          <el-input
            v-model="mbCaseMoldModel.moldName"
            placeHolder="请输入该字段"
          ></el-input>
        </el-form-item>
        <el-form-item label="模具编码">
          <el-input
            v-model="mbCaseMoldModel.moldCode"
            placeHolder="请输入该字段"
          ></el-input>
        </el-form-item>
        <el-form-item label="底图">
          <el-upload
            style="display: inline-block;"
            :http-request="handleBackImgUploadFile"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-picture"
              >点击上传</el-button
            >
          </el-upload>
          <el-avatar
            style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
            v-if="mbCaseMoldModel.backImg"
            shape="square"
            size="100"
            fit="contain"
            :src="mbCaseMoldModel.backImg"
          ></el-avatar>
        </el-form-item>
        <el-form-item label="顶层透明图">
          <el-upload
            style="display: inline-block;"
            :http-request="handleOverlayImgUploadFile"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-picture"
              >点击上传</el-button
            >
          </el-upload>
          <el-avatar
            style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
            v-if="mbCaseMoldModel.overlayImg"
            shape="square"
            size="100"
            fit="contain"
            :src="mbCaseMoldModel.overlayImg"
          ></el-avatar>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRowVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveRow">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMbCaseMold,
  getMbCaseMoldByPage,
  removeMbCaseMoldById,
  updateMbCaseMoldById
} from "@/api/admin-api/MbCaseMoldApi";
import { getBrandByPage } from "@/api/admin-api/BrandApi";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";

export default {
  name: "MbCaseMold",
  data() {
    return {
      brands: [],
      pageVo: {
        current: 1,
        size: 20,
        total: 0, //总数量
        pages: 0, //总页数
        orders: [{ column: 'create_time' }], //排序字段
        brandId: "",
        moldCode: "",
        moldName: ""
      },
      editRowVisible: false,
      mbCaseMoldModel: {
        id: null,
        brandId: null,
        moldName: null,
        moldCode: null,
        backImg: null,
        overlayImg: null,
        createTime: null,
        updateTime: null,
        dataState: null,
        lastVersion: null,
        createUserId: null
      },
      loadingTable: false,
      mbCaseMoldList: []
    };
  },
  methods: {
    onSearch() {
      this.loadMbCaseMoldList();
    },
    onClearSearchForm() {
      this.pageVo = this.$options.data().pageVo;
      this.loadMbCaseMoldList();
    },
    brandFormatter(row) {
      return this.brands.find(item => item.id === row.brandId).brandName;
    },
    handleOverlayImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.mbCaseMoldModel.overlayImg =
              "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    handleBackImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.mbCaseMoldModel.backImg =
              "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    async loadBrands() {
      return new Promise(resolve => {
        getBrandByPage({ size: 200 }).then(data => {
          // this.brands = data.records;
          resolve(data.records);
        });
      });
    },
    onPaging(currentPage) {
      // 页码改变
      this.pageVo.current = currentPage;
      this.loadMbCaseMoldList();
    },
    handleSizeChange(val) {
      //页大小改变
      this.pageVo.size = val;
      this.loadMbCaseMoldList();
    },
    onSaveRow() {
      //保存或更新
      if (this.mbCaseMoldModel.id) {
        //更新
        this.$loading();
        updateMbCaseMoldById(this.mbCaseMoldModel)
          .then(() => {
            this.$message.success("操作成功");
            this.loadMbCaseMoldList();
            this.$loading().close();
            this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      } else {
        //保存
        this.$loading();
        addMbCaseMold(this.mbCaseMoldModel)
          .then(() => {
            this.$message.success("操作成功");
            this.$loading().close();
            this.loadMbCaseMoldList();
            this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      }
    },
    showAddRowDialog() {
      //显示添加行对话框
      this.editRowVisible = true;
      this.mbCaseMoldModel = this.$options.data().mbCaseMoldModel;
    },
    loadMbCaseMoldList() {
      this.loadingTable = true;
      getMbCaseMoldByPage(this.pageVo)
        .then(data => {
          this.mbCaseMoldList = data.records;
          this.pageVo.current = data.current;
          this.pageVo.pages = data.pages;
          this.pageVo.total = Number(data.total);
          this.loadingTable = false;
        })
        .catch(() => {
          this.loadingTable = false;
        });
    },
    onEditRow(row) {
      //编辑行
      this.mbCaseMoldModel = row;
      this.editRowVisible = true;
    },
    onDeleteRow(row) {
      //删除行
      this.$confirm("确定要删除当前行吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$loading();
        removeMbCaseMoldById(row.id)
          .then(() => {
            this.loadMbCaseMoldList();
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    }
  },
  async mounted() {
    this.brands = await this.loadBrands();
    this.loadMbCaseMoldList();
  }
};
</script>
<style scoped></style>
